/**
 * author: zhangyy-g@grandsoft.com.cn
 * description: dialog
 */
(function ($) {
    var Dialog = function (options) {
        var self = this
        self.__options = {
            width: 560,
            height: null,
            title: '',
            showTitle: true,
            showFooter: true,
            cssClass: null,
            showClose: true,
            message: '你木有事做吗？你真的木有事做吗？缅怀青春吧~',
            isFixed: true,
            denyEsc: false,
            modal: true,
            isAlert: false,
            isConfirm: false,
            okText: '确&nbsp;&nbsp;定',
            cancelText: '取&nbsp;&nbsp;消',
            okClass: 'gbutton-action',
            okCallback: jQuery.noop,
            cancelCallback: jQuery.noop,
            closeCallback: jQuery.noop
        };
        if (options.isAlert || options.isConfirm) {
            options.width = 360;
            options.height = 80;
        }
        $.extend(self.__options, options);
        self.init();
    }
    Dialog.prototype = {
        init: function () {
            var self = this;
            //获得渲染页面
            var element = self.element = self.__getElement();
            this.bindEvent();

            //保持单例
            DialogManager.keepSingle(self);

            // 添加到页面
            $(document.body).append(element);

            // 定位
            this.__offset();

            //拖动
            this.__dragable();

            //是否显示关闭图标
            if (!self.__options.showClose) {
                self.find('.close').hide();
            }

            // 显示
            self.show();
        },

        //获得渲染页面
        __getElement: function () {
            var self = this;
            var options = self.__options;
            var message = options.message;

            var fragment = ['<div class="mod-dialog">', '<div class="wrapper">', '<div class="header">', '<h3 class="title">',
                options.title || '', '</h3>',
                '<a class="close"></a>', '</div>', '<div class="content">',
                '</div>', '</div>', '</div>'].join('');

            var element = $(fragment);

            if (options.showFooter) {
                if (options.isAlert) {
                    element.addClass('dialog-alert');
                    element.find('.wrapper').append('<div class="footer clr"><button class="ok ' + options.okClass + '">' + options.okText + '</button></div>');
                } else {
                    element.find('.wrapper').append('<div class="footer clr"><button class="cancel">' + options.cancelText + '</button></div>');
                    element.find('.footer').append('<button class="ok ' + options.okClass + '">' + options.okText + '</button>');
                    if (options.isConfirm) {
                        options.isConfirm && element.addClass('dialog-confirm');
                    }
                }
            }

            if (typeof message == 'string') {
                if (options.isAlert || options.isConfirm) {
                    message = '<div class="dialog-warn"></div><div class="dialog-warn-txt">' + message + '</div>'
                }
                element.find('.content').html(message);
            } else {
                $(message).appendTo(element.find('.content'));
            }

            if (!options.showFooter) {
                element.find('.footer').remove();
            }
            //是否显示头部
            if (!options.showTitle) {
                element.find('.header').remove();
            }
            // 设置样式
            element.css({
                width: options.width
            });

            if (options.height !== null) {
                element.find('.content').css({
                    height: options.height
                });
            }
            if (options.isFixed !== true) {
                element.css({
                    position: 'absolute'
                });
            }

            options.cssClass && element.addClass(options.cssClass);

            return element;
        },

        //重新定位
        reLocation: function () {
            // 定位
            this.__offset();
        },

        __dragable: function () {
            var element = this.element
            element.draggable && element.draggable({
                containment: 'window',
                handle: '.header'
            });
        },

        //居中
        __offset: function () {
            var self = this,
                element = self.element,
                top = self.__options.top,
                left = self.__options.left;
            if (left == null) {
                left = ($(window).width() - self.element.outerWidth()) / 2;
                left = Math.max(0, left);
            }

            // 如果TOP没有指定 那么垂直居中
            if (top == null) {
                top = ($(window).height() - self.element.outerHeight()) / 3;
                top = Math.max(0, top);
            }

            // 如果元素不是fixed定位 那么加上滚动条距离
            if (this.element.css('position') != 'fixed') {
                left += jQuery(document).scrollLeft();
                top += jQuery(document).scrollTop();
            }

            element.css({left: left, top: top});
        },

        //设置宽度
        setWidth: function (width) {
            var self = this
            // 设置样式
            self.element.css({
                width: width
            });
            self.__options.width = width;

            self.__offset();
        },

        //获得头部
        getHeader: function () {
            return this.find('.wrapper > .header');
        },

        //获得尾部
        getFooter: function () {
            return this.find('.wrapper > .footer');
        },

        //获得遮罩
        getMaskLayer: function () {
            return MaskLayer.getElement();
        },

        //显示
        show: function () {
            var self = this
            if (self.__options.modal === true) MaskLayer.show();
            self.__offset();
        },

        //关闭
        close: function (keepMask) {
            var self = this;
            !keepMask && MaskLayer.hide();
            var element = self.element;
            element.remove();
            self.__options.closeCallback.call(self);
        },

        //查找元素
        find: function (rule) {
            return this.element.find(rule);
        },

        //确认
        confirm: function () {
            var self = this;
            self.element.find('.footer .ok').trigger('click');
        },


        bindEvent: function () {
            var self = this
            self.find('.header .close').click(function () {
                self.close();
                return false;
            })

            self.find('.footer .ok').click(function () {
                if (self.__options.okCallback.call(self) !== false) {
                    self.close();
                }
                return false
            })
            self.find('.footer .cancel').click(function () {
                if (self.__options.cancelCallback.call(self) !== false) {
                    self.close();
                }
                return false
            })

            var contextProxy = function () {
                // 防止销魂元素后导致内存泄露（因为RESIZE事件是注册在WINDOW对象上 而不是ELEMENT元素上）
                if (self.element.parent().size() === 0) {
                    jQuery(window).unbind('resize', contextProxy)
                }
                else if (self.element.is(':visible')) {
                    self.__offset()
                }
            }
            $(window).resize(contextProxy)
        }
    }

    //遮罩层
    var MaskLayer = {
        getElement: function () {
            var self = this;
            if (!self.element) {
                self.element = $('#mod-dialog-masklayer');
                if (self.element.size() == 0) {
                    self.element = $('<div class="mod-dialog-masklayer"><iframe frameborder="0" width="100%" height="100%" style="z-index:1; position:absolute;"></iframe></div>').appendTo($(document.body));
                }
            }
            return self.element
        },
        show: function () {
            this.getElement().show()
        },
        hide: function () {
            this.getElement().hide()
        }
    }

    // 弹窗单例管理
    var DialogManager = {
        present: null,

        keepSingle: function (dialog) {
            if (this.present instanceof Dialog) {
                this.present.close();
                this.present = null;
            }
            this.present = dialog;
            this.bindEvent();
        },

        escCancel: function (e) {
            if (e.keyCode == 27 && DialogManager.present) {
                var dialog = DialogManager.present;

                dialog.hide();
            }
        },

        bindEvent: function () {
            $(document).keydown(this.escCancel);
            this.bindEvent = jQuery.noop;
        }
    }

    // export public method
    App.common.modules.Dialog = Dialog;

    //使用方法
    /*new App.common.modules.Dialog({
        //showTitle: false,
        //showFooter: false,
        isConfirm: true,
        message: '我是message',
        okCallback: function() {
            alert('ok')
            return false
        },
        cancelCallback: function() {
            alert('cancel')
        }
    })*/

})(jQuery)
